import React, { useState, useEffect } from 'react';
import { Button, Toast, Dialog } from 'antd-mobile';
import { BellOutline, CloseOutline } from 'antd-mobile-icons';
import { reminderService, type ReminderItem } from '../utils/reminderService';
import dayjs from 'dayjs';
import './GlobalReminderDisplay.css';

const GlobalReminderDisplay: React.FC = () => {
  const [reminders, setReminders] = useState<ReminderItem[]>([]);
  const [isVisible, setIsVisible] = useState(false);
  const [hasActiveReminders, setHasActiveReminders] = useState(false);

  // 星期数据
  const weekDays = [
    { label: '星期日', value: 0 },
    { label: '星期一', value: 1 },
    { label: '星期二', value: 2 },
    { label: '星期三', value: 3 },
    { label: '星期四', value: 4 },
    { label: '星期五', value: 5 },
    { label: '星期六', value: 6 },
  ];

  // 加载提醒数据
  useEffect(() => {
    const loadReminders = () => {
      const allReminders = reminderService.getReminders();
      setReminders(allReminders);
      setHasActiveReminders(allReminders.some(r => r.isActive));
    };

    // 初始加载
    loadReminders();

    // 定期更新（每3秒检查一次）
    const interval = setInterval(loadReminders, 3000);

    return () => clearInterval(interval);
  }, []);

  // 切换提醒状态
  const handleToggleReminder = (id: string) => {
    const reminder = reminders.find(r => r.id === id);
    if (reminder) {
      reminderService.updateReminder(id, { isActive: !reminder.isActive });
      const updatedReminders = reminderService.getReminders();
      setReminders(updatedReminders);
      setHasActiveReminders(updatedReminders.some(r => r.isActive));
      reminderService.restartReminderCheck();
      
      Toast.show({ 
        content: `提醒已${reminder.isActive ? '禁用' : '启用'}`, 
        duration: 1500 
      });
    }
  };

  // 删除提醒
  const handleDeleteReminder = (id: string) => {
    Dialog.confirm({
      title: '确认删除',
      content: '确定要删除这个提醒吗？',
      confirmText: '删除',
      cancelText: '取消',
      onConfirm: () => {
        reminderService.removeReminder(id);
        const updatedReminders = reminderService.getReminders();
        setReminders(updatedReminders);
        setHasActiveReminders(updatedReminders.some(r => r.isActive));
        reminderService.restartReminderCheck();
        Toast.show({ content: '提醒已删除', duration: 1500 });
      }
    });
  };

  // 格式化时间显示
  const formatTime = (reminder: ReminderItem) => {
    const hour12 = reminder.hour24 % 12 === 0 ? 12 : reminder.hour24 % 12;
    return `${hour12.toString().padStart(2, '0')}:${reminder.minute.toString().padStart(2, '0')} ${reminder.period}`;
  };

  // 格式化日期显示
  const formatDays = (days: number[]) => {
    return days.map(day => weekDays[day].label.slice(2)).join('、');
  };

  // 获取下一个提醒时间
  const getNextReminderTime = (): ReminderItem | null => {
    const now = dayjs();
    const today = now.day();
    const currentTime = now.hour() * 60 + now.minute();
    
    let nextReminder: ReminderItem | null = null;
    let minTimeDiff = Infinity;
    
    reminders.forEach(reminder => {
      if (!reminder.isActive) return;
      
      // 检查今天是否在提醒的日期列表中
      if (reminder.days.includes(today)) {
        const reminderTime = reminder.hour24 * 60 + reminder.minute;
        const timeDiff = reminderTime - currentTime;
        
        // 如果时间还没到，且是最接近的
        if (timeDiff > 0 && timeDiff < minTimeDiff) {
          minTimeDiff = timeDiff;
          nextReminder = reminder;
        }
      }
    });
    
    return nextReminder;
  };

  const nextReminder = getNextReminderTime();

  if (reminders.length === 0) {
    return null;
  }

  return (
    <div className="global-reminder-container">
      {/* 提醒按钮 */}
      <div className="reminder-toggle-btn" onClick={() => setIsVisible(!isVisible)}>
        <BellOutline className={`reminder-icon ${hasActiveReminders ? 'active' : ''}`} />
        {hasActiveReminders && <div className="reminder-badge" />}
      </div>

      {/* 提醒列表弹窗 */}
      {isVisible && (
        <div className="reminder-popup">
          <div className="reminder-popup-header">
            <h3>训练提醒</h3>
            <CloseOutline 
              className="close-btn" 
              onClick={() => setIsVisible(false)} 
            />
          </div>
          
          <div className="reminder-popup-content">
            {nextReminder && (
              <div className="next-reminder-info">
                <div className="next-reminder-title">下一个提醒</div>
                <div className="next-reminder-time">
                  {formatTime(nextReminder)} - {formatDays(nextReminder.days)}
                </div>
              </div>
            )}
            
            <div className="reminder-list">
              {reminders.map(reminder => (
                <div key={reminder.id} className={`reminder-item ${!reminder.isActive ? 'disabled' : ''}`}>
                  <div className="reminder-info">
                    <div className="reminder-time">{formatTime(reminder)}</div>
                    <div className="reminder-days">{formatDays(reminder.days)}</div>
                    <div className="reminder-status">
                      {reminder.isActive ? '已启用' : '已禁用'}
                    </div>
                  </div>
                  <div className="reminder-actions">
                    <Button
                      size="small"
                      color={reminder.isActive ? 'default' : 'primary'}
                      onClick={() => handleToggleReminder(reminder.id)}
                    >
                      {reminder.isActive ? '禁用' : '启用'}
                    </Button>
                    <Button
                      size="small"
                      color="danger"
                      onClick={() => handleDeleteReminder(reminder.id)}
                    >
                      删除
                    </Button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default GlobalReminderDisplay;
